package fr.ufc.kiestla.ta;

import fr.ufc.kiestla.TypeUser;
import fr.ufc.kiestla.SeleniumTool;
import fr.ufc.kiestla.Signalement;
import fr.ufc.kiestla.Module;
import fr.ufc.kiestla.Connexion;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.support.ui.Select;

public class SignalementDoublon {
  private WebDriver driver;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();
  private Connexion etudiant;
  private Connexion referant;
  private Module module;
  
  
  @Before
  public void setUp() throws Exception {
    driver = new HtmlUnitDriver();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    etudiant = SeleniumTool.createUser(driver, TypeUser.ETUDIANT);
    referant = SeleniumTool.createUser(driver, TypeUser.ENSEIGNANT);
    module = SeleniumTool.createModule(driver, referant.getLogin());
	SeleniumTool.connect(driver, referant);
	SeleniumTool.ajouterEtudiantModule(driver, module, etudiant);
	SeleniumTool.signalerEtudiant(driver, new Signalement(module, etudiant, "2014-06-11"));
  }

  @Test
  public void testSignalement() throws Exception {
	SeleniumTool.connect(driver, referant);
	SeleniumTool.signalerEtudiant(driver, new Signalement(module, etudiant, "2014-06-11"));
    try {
        assertEquals("Etudiant deja sinale", driver.findElement(By.xpath("//div[@class=\"alert alert-danger alert-dismissable\"]/p")).getText());
    } catch (Error e) {
      verificationErrors.append(e.toString());
    }
  }

  @After
  public void tearDown() throws Exception {
	SeleniumTool.deleteModule(driver, module);
	SeleniumTool.deleteUser(driver, referant);
	SeleniumTool.deleteUser(driver, etudiant);
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private boolean isAlertPresent() {
    try {
      driver.switchTo().alert();
      return true;
    } catch (NoAlertPresentException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}
